package com.huihui.fragment;

import android.content.ContentValues;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.huihui.R;
import com.huihui.adapter.DouyinAdapter;
import com.huihui.adapter.VideoCommentAdapter;
import com.huihui.bean.SmallVideo;
import com.huihui.bean.VideoComment;
import com.huihui.bean.ZuJi;
import com.huihui.bean.ZuJiInfo;
import com.huihui.datamanager.AppManager;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.utils.ToolUtils;
import com.huihui.widget.OnViewPagerListener;
import com.huihui.widget.SwipeRecyclerView;
import com.huihui.widget.ViewPagerLayoutManager;
import com.huihui.widget.footerView.SimpleFooterView;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/8/15.
 * 小视频
 */

public class SmallVideoSearchFragment extends BaseFragment {

    private RecyclerView recycler;
    private List<SmallVideo> mList = new ArrayList<>();
    private DouyinAdapter adapter;
    ViewPagerLayoutManager mLayoutManager;

    private int pageIndex = 1;
    private String keyWord;
    private long video_id;
    private List<VideoComment> commentList;
    private VideoCommentAdapter commentAdapter;
    private SmallVideo smallVideo;
    private EditText inputTextComment;
    private VideoComment videoComment;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_small_video_search,container,false);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initView(View view) {
        recycler = view.findViewById(R.id.recycler);

        mLayoutManager = new ViewPagerLayoutManager(getContext(), OrientationHelper.VERTICAL);
        adapter = new DouyinAdapter(getActivity(), mList);
        commentList = new ArrayList<>();
        recycler.setLayoutManager(mLayoutManager);
        recycler.setAdapter(adapter);
        commentList = new ArrayList<>();
    }
    public void setKeyWords(String keyWords){
        keyWord = keyWords;
        //初始化pageIndex = 1
        pageIndex = 1;
        initData();
    }
    private void initData() {
        if(TextUtils.isEmpty(keyWord)){
            return;
        }
        OkHttpRequest.getInstance().videoList(HttpContants.video_list, keyWord, 1, pageIndex, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject != null) {
                        List<SmallVideo> list = AppManager.getGson().fromJson(jsonObject.getString(HttpContants.DATA), new TypeToken<List<SmallVideo>>() {
                        }.getType());
                        if (list != null) {
                            if (pageIndex == 1) {
                                mList.clear();
                                mList.addAll(list);
                                adapter.notifyDataSetChanged();
                            } else {
                                mList.addAll(list);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private PopupWindow commentPop = null;
    private View commentLayout = null;
    private SwipeRecyclerView commentRecycle;
    private void showPingLunPop(final long videoId) {
        if (commentPop == null) {
            commentLayout = LayoutInflater.from(getContext()).inflate(R.layout.douyin_pinglun_listview, null);
            int height = (int) (ToolUtils.getHeight(getContext()) * 0.5);
            commentRecycle = commentLayout.findViewById(R.id.douyin_pinglun_listview);
            ViewGroup.LayoutParams layoutParams = commentRecycle.getLayoutParams();
            layoutParams.height = height;
            commentRecycle.setLayoutParams(layoutParams);
            commentRecycle.getRecyclerView().setLayoutManager(new LinearLayoutManager(getContext()));
            commentAdapter = new VideoCommentAdapter(getContext(), commentList, videoId);
            commentRecycle.setAdapter(commentAdapter);
            commentPop = new PopupWindow(commentLayout, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
            commentPop.setOutsideTouchable(true);
            commentPop.setFocusable(true);
            commentPop.setBackgroundDrawable(new ColorDrawable());
        }
        commentPop.showAtLocation(recycler, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        TextView commentNum = commentLayout.findViewById(R.id.comment_num);
        commentNum.setText(String.valueOf(smallVideo.getComment_num()));

        inputTextComment = commentLayout.findViewById(R.id.input_textview);
        inputTextComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String comment = v.getText().toString();
                    if (TextUtils.isEmpty(comment)) return false;
                    if (videoComment == null) {

                        addComment(comment, 0);
                    } else {
                        addComment(comment, videoComment.getCom_id());
                    }
                    inputTextComment.getText().delete(0, comment.length());
                }
                return false;
            }
        });
        commentAdapter.setPingLunClickListener(new VideoCommentAdapter.OnPinglunClickListener() {
            @Override
            public void onClick(int position) {
                videoComment = commentList.get(position);
                inputTextComment.requestFocus();
                inputTextComment.setHint("回复 " + videoComment.getUser_nick_name());
                inputTextComment.post(new Runnable() {
                    @Override
                    public void run() {
                        showkeyboard(inputTextComment);
                    }
                });

            }


        });
        commentRecycle.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                commentCurrentPage = 1;
                getCommentList(videoId);
            }

            @Override
            public void onLoadMore() {
                commentCurrentPage ++;
                getCommentList(videoId);
            }
        });


    }

    private void addComment(String comment, int parent_comment_id) {
        OkHttpRequest.getInstance().addVideoComment(HttpContants.video_addComment, AppManager.getUserInfo().getUser_id(),
                video_id, parent_comment_id, comment, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        if(videoComment != null){
                            inputTextComment.setHint("说说你的看法");
                        }
                        videoComment = null;
                        commentCurrentPage = 1;
                        getCommentList(video_id);
                    }
                });
    }
    private void initListener() {
        mLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onPageSelected(int position, boolean isBottom) {
                if (isBottom) {
                    pageIndex = position + 1;
                    pageIndex++;
                    initData();
                }
            }
        });
        adapter.setOnPingLunListener(new DouyinAdapter.onPingLunListener() {
            @Override
            public void onCLick(int position) {
                smallVideo = mList.get(position);
                video_id = smallVideo.getVideo_id();
                if (commentAdapter != null) {

                    commentList.clear();
                    commentAdapter.notifyDataSetChanged();
                }
                showPingLunPop(video_id);
                getCommentList(video_id);
            }
        });
    }

    private int commentPagesize = 10;
    private int commentCurrentPage = 1;

    private void getCommentList(long videoId) {
        OkHttpRequest.getInstance().getVideoComment(HttpContants.video_getComment,
                videoId, commentPagesize, commentCurrentPage, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            if (jsonObject != null) {
                                List<VideoComment> list = AppManager.getGson().fromJson(jsonObject.getString(HttpContants.DATA), new TypeToken<List<VideoComment>>() {
                                }.getType());
                                if (list != null && list.size() > 0) {
                                    if (pageIndex == 1) {
                                        commentList.clear();
                                        commentList.addAll(list);
                                    } else {
                                        commentList.addAll(list);
                                    }
                                    saveZujiInfo(pageIndex);
                                    commentAdapter.notifyDataSetChanged();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    public void setRecycleView(SwipeRecyclerView recyclerView) {
        //set layoutManager
        recyclerView.getRecyclerView().setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置emptyView
//        TextView textView = new TextView(getActivity());
//        textView.setText("没有更多数据");
//        recyclerView.setEmptyView(textView);

        //设置footerView
        recyclerView.setFooterView(new SimpleFooterView(getActivity()));
        //设置去除footerView 的分割线
//        recyclerView.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
//                super.onDraw(c, parent, state);
//                Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//                paint.setColor(0xFFEECCCC);
//
//                Rect rect = new Rect();
//                int left = parent.getPaddingLeft();
//                int right = parent.getWidth() - parent.getPaddingRight();
//                final int childCount = parent.getChildCount() - 1;
//                for (int i = 0; i < childCount; i++) {
//                    final View child = parent.getChildAt(i);
//
//                    //获得child的布局信息
//                    final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
//                    final int top = child.getBottom() + params.bottomMargin;
//                    final int itemDividerHeight = 1;//px
//                    rect.set(left + 50, top, right - 50, top + itemDividerHeight);
//                    c.drawRect(rect, paint);
//                }
//            }
//        });
    }
    private void saveZujiInfo(int position) {
        if(mList.size() < position){
            return;
        }
        SmallVideo smallVideo = mList.get(--position);
        long video_id = smallVideo.getVideo_id();
        ZuJi zuJi = new ZuJi();
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        List<ZuJi> zuJiList = DataSupport.where("time = ?", sdf.format(new Date())).find(ZuJi.class);
        if (zuJiList.size() > 0) {
            //存在
        } else {
            //不存在
            zuJi.setTime(sdf.format(new Date()));
            zuJi.save();
        }
        ZuJiInfo zuJiInfo = new ZuJiInfo();
        zuJiInfo.setCuttentTime(sdf.format(new Date()));
        zuJiInfo.setClass_id(1);
        zuJiInfo.setZujiId(video_id);
        zuJiInfo.setContent(smallVideo.getVideo_title());
        zuJiInfo.setName(smallVideo.getUser_nick_name());
        zuJiInfo.setIconPath(smallVideo.getUser_head_photo());
        zuJiInfo.setComment_num(smallVideo.getComment_num());
        zuJiInfo.setAuthor_head_img(smallVideo.getUser_head_photo());
        zuJiInfo.setTime(smallVideo.getUploadTime());
        zuJiInfo.setCuttentTime(sdf.format(new Date()));

        List<ZuJiInfo> list = DataSupport.where("class_id = ? and zujiId = ?", "1",
                String.valueOf(smallVideo.getVideo_id())).find(ZuJiInfo.class);
        if (list.size() > 0) {
            ContentValues vaules = new ContentValues();
            vaules.put("cuttentTime", sdf.format(new Date()));
            DataSupport.updateAll(ZuJiInfo.class, vaules, "class_id = ? and zujiId = ?", "1",
                    String.valueOf(video_id));
        } else {
            zuJiInfo.save();
        }



    }
}
